<template>
  <div>
    <el-drawer
      :with-header="false"
      :destroy-on-close="true"
      :wrapper-closable="false"
      :visible.sync="drawerVisible"
      size="1000px"
    >
      <div class="drawerForm">
        <div class="pageTitle">
          <div class="titleText">{{ formData.displayName }}</div>
        </div>
        <el-collapse v-model="activeName" class="mainContent">
          <el-collapse-item title="芯片信息" name="first">
            <el-form
              ref="formData"
              :disabled="drawerType === 'view'"
              :model="formData"
              :rules="rules"
              label-width="93px"
              label-suffix="："
            >
              <el-row :gutter="80">
                <el-col :span="12">
                  <el-form-item label="芯片名称" prop="displayName">
                    <el-input
                      v-model="formData.displayName"
                      class="show-word-limit"
                      :maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="芯片型号" prop="model">
                    <el-input v-model="formData.model" class="show-word-limit" :maxlength="50" show-word-limit />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="80">
                <el-col :span="12">
                  <el-form-item label="芯片分类" prop="displayCategory">
                    <el-autocomplete
                      v-model="formData.displayCategory"
                      class="w100 show-word-limit"
                      :maxlength="20"
                      show-word-limit
                      :fetch-suggestions="querySearch"
                      placeholder="请输入内容"
                    ></el-autocomplete>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <el-form-item label="芯片类型" prop="type">
                    <el-select v-model="formData.type" class="w100" @change="handleChange">
                      <el-option label="主控芯片" :value="1"></el-option>
                      <el-option label="被控芯片" :value="2"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col> -->
                <el-col :span="12">
                  <el-form-item label="厂家名称" prop="manufacturer">
                    <el-input
                      v-model="formData.manufacturer"
                      class="show-word-limit"
                      :maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="描述" prop="description">
                <el-input
                  v-model="formData.description"
                  type="textarea"
                  class="show-word-limit"
                  :maxlength="255"
                  show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item label="概述" prop="overview">
                <el-input
                  v-model="formData.overview"
                  type="textarea"
                  :rows="8"
                  class="show-word-limit"
                  :maxlength="2000"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <el-collapse-item title="芯片引脚" name="second">
            <el-image
              :key="pinPicTimer"
              class="picture"
              :src="formData.pinFiles.length > 0 ? 'data:image/png;base64,' + formData.pinFilesBase64 : ''"
              :preview-src-list="
                formData.pinFiles.length > 0 ? ['data:image/png;base64,' + formData.pinFilesBase64] : []
              "
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <el-form v-if="drawerType === 'edit'">
              <el-form-item label="引脚图：">
                <el-upload
                  ref="pinFiles"
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  :show-file-list="false"
                  :accept="uploadAccept"
                  :on-exceed="(files) => handleExceed(files, 'pinFiles')"
                  :http-request="(require) => handleUploadFiles(require, 'pinFiles')"
                >
                  <div slot="tip" class="el-upload__tip">
                    只能上传{{ uploadAccept.split(',').join(' ') }}文件，且单个文件不超过 20 MB
                  </div>
                  <el-button type="primary">
                    上传图片
                    <i class="el-icon-upload el-icon--right" />
                  </el-button>
                  <el-button
                    v-show="formData.pinFiles.length > 0"
                    plain
                    type="danger"
                    @click.stop="handleDel('pinFiles')"
                  >
                    删除图片
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <el-collapse-item v-if="formData.type === 1" title="芯片时钟" name="third">
            <clockSetting
              ref="clockSetting"
              :key="clockPicTimer"
              :clock-pic="formData.clockParameterFilesBase64"
              :disabled="true"
              :is-check="false"
              :form-data="clockFormData"
              :form-fields="clockParameters"
            />
            <el-form style="margin-top: 10px" label-suffix="：">
              <el-form-item v-if="drawerType === 'edit'" label="时钟配置图">
                <el-upload
                  ref="clockParameterFiles"
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  :show-file-list="false"
                  :accept="uploadAccept"
                  :on-exceed="(files) => handleExceed(files, 'clockParameterFiles')"
                  :http-request="(require) => handleUploadFiles(require, 'clockParameterFiles')"
                >
                  <div slot="tip" class="el-upload__tip">
                    只能上传{{ uploadAccept.split(',').join(' ') }}文件，且单个文件不超过 20 MB
                  </div>
                  <el-button type="primary">
                    上传图片
                    <i class="el-icon-upload el-icon--right" />
                  </el-button>
                  <el-button
                    v-show="formData.clockParameterFiles.length > 0"
                    plain
                    type="danger"
                    @click.stop="handleDel('clockParameterFiles')"
                  >
                    删除图片
                  </el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="时钟配置参数">
                <el-button type="primary" @click="handleClick('parameters')">配置参数</el-button>
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <el-collapse-item v-else title="主要性能参数" name="fourth">
            <el-image
              :key="parametersPicTimer"
              class="picture"
              :src="
                formData.performanceParameterFiles.length > 0
                  ? 'data:image/png;base64,' + formData.performanceParameterFilesBase64
                  : ''
              "
              :preview-src-list="
                formData.performanceParameterFiles.length > 0
                  ? ['data:image/png;base64,' + formData.performanceParameterFilesBase64]
                  : []
              "
            >
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
            <el-form v-if="drawerType === 'edit'">
              <el-form-item label="主要性能参数图：">
                <el-upload
                  ref="performanceParameterFiles"
                  class="upload-demo"
                  action="#"
                  :limit="1"
                  :show-file-list="false"
                  :accept="uploadAccept"
                  :on-exceed="(files) => handleExceed(files, 'performanceParameterFiles')"
                  :http-request="(require) => handleUploadFiles(require, 'performanceParameterFiles')"
                >
                  <div slot="tip" class="el-upload__tip">
                    只能上传{{ uploadAccept.split(',').join(' ') }}文件，且单个文件不超过 20 MB
                  </div>
                  <el-button type="primary">
                    上传图片
                    <i class="el-icon-upload el-icon--right" />
                  </el-button>
                  <el-button
                    v-show="formData.performanceParameterFiles.length > 0"
                    plain
                    type="danger"
                    @click.stop="handleDel('performanceParameterFiles')"
                  >
                    删除图片
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-form>
          </el-collapse-item>
          <el-collapse-item v-if="formData.type === 1" :title="'芯片引脚复用与接口资源'" name="fiveth">
            {{ drawerType === 'view' ? '可通过下载芯片定义文件查看' : '可通过修改芯片定义文件更新' }}
          </el-collapse-item>
          <el-collapse-item :title="'电路生成模块芯片型号'" name="sixth">
            <div>
              <el-button
                type="text"
                icon="el-icon-plus"
                v-if="drawerType === 'edit'"
                @click="handleClick('addMapping',{id:formData.circuitGenerationModuleChipList.length + 1})"
              >
                添加一个型号名称
              </el-button>
              <el-table
                ref="singleTable"
                :data="tableData"
                highlight-current-row
                style="width: 100%"
              >
                <el-table-column type="index" label="序号" width="100" />
                <el-table-column label="芯片型号">
                  <template slot-scope="scope">
                    <el-input
                      v-model="scope.row.model"
                      class="show-word-limit"
                      :maxlength="50"
                      show-word-limit
                      :disabled="drawerType === 'view'"
                      @input="handleInputChange(scope.row, scope.$index)"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="200">
                  <template slot-scope="scope">
                    <el-button
                      type="text"
                      :disabled="drawerType === 'view'"
                      @click="handleClick('deleteMapping', scope)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
          <!-- <el-collapse-item
            :title="formData.type === 1 ? '芯片引脚复用与接口资源' : '芯片配置参数与控制方式'"
            name="fiveth"
          >
            可通过下载芯片定义文件查看
          </el-collapse-item> -->
        </el-collapse>
        <div class="drawerFooter" align="right">
          <el-button
            v-if="formData.type === 1 && drawerType === 'view'"
            type="primary"
            @click="handleClick('download')"
          >
            下载芯片定义文件
          </el-button>
          <el-button v-show="drawerType === 'view'" @click="drawerVisible = false">退出页面</el-button>
          <el-button v-show="drawerType === 'edit'" type="primary" @click="handleClick('submit')">确定</el-button>
          <el-button v-show="drawerType === 'edit'" @click="drawerVisible = false">取消</el-button>
        </div>
      </div>
    </el-drawer>

    <clockConfigurationParameters ref="clockConfigurationParameters" @submit="handleClick" />
  </div>
</template>

<script>
import { uploadFile } from '@/api/system-management'
import { updateChip } from '@/api/project-management'
import { downLoadFile, fileDownload } from '@/utils/download'
import clockSetting from './clockSetting.vue'
import clockConfigurationParameters from './clockConfigurationParameters.vue'
import defaultSettings from '@/settings'
import { generateUUID, postMessage, receivedMessage } from '@/utils/index'
export default {
  components: { clockSetting, clockConfigurationParameters },
  props: {
    categoryList: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      drawerType: '',
      drawerVisible: false,
      activeName: ['first'],
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadAccept: '.jpg,.jpeg,.png',
      pinPicTimer: null,
      clockPicTimer: null,
      parametersPicTimer: null,
      formData: {
        pinFiles: [],
        clockParameterFiles: [],
        performanceParameterFiles: [],
        deleteMappingIdArray: [],
        addMappingArray: []
      },
      tableData: [],
      rules: {
        displayName: [{ required: true, message: '请输入芯片名称', trigger: 'blur' }],
        model: [{ required: true, message: '请输入芯片型号', trigger: 'blur' }],
        displayCategory: [{ required: true, message: '请选择芯片分类', trigger: ['change', 'blur'] }],
        type: [{ required: true, message: '请选择芯片类型', trigger: ['change', 'blur'] }],
        manufacturer: [{ required: true, message: '请输入厂家名称', trigger: 'blur' }]
      },
      clockParameters: [],
      clockFormData: {},
      uploadFileRequestId: generateUUID(),
      uploadFileSetting: {},
      updateChipRequestId: generateUUID(),
      downloadFileRequestId: generateUUID()
    }
  },
  mounted() {
    receivedMessage(this.dataHandle)
  },
  methods: {
    dataHandle(result) {
      let self = this
      let e = defaultSettings.isWPF ? result : { data: JSON.parse(result) }
      if (e.data.webInfo.requestId === self.uploadFileRequestId) {
        const { fileName, require } = self.uploadFileSetting
        self.$set(self.formData, fileName, [
          {
            uid: require.file.uid,
            fileType: e.data.response.data.fileType,
            name: e.data.response.data.name,
            fileName: e.data.response.data.name,
            url: e.data.response.data.url,
            path: e.data.response.data.url
          }
        ])
        self.$set(self.formData, fileName + 'Base64', e.data.response.data.base64)
        self[fileName + 'Timer'] = new Date().getTime()
      } else if (e.data.webInfo.requestId === self.updateChipRequestId) {
        if (e.data.response.success) {
          self.drawerVisible = false
          self.$notify.success('修改芯片信息成功')
          self.$emit('refresh', self.formData.type, self.formData.displayCategory)
        } else {
          self.$notify.error(e.data.response.message)
        }
      } else if (e.data.webInfo.requestId === self.downloadFileRequestId) {
        let res = e.data.response
        if (res.success) {
          var bytes = new Uint8Array(
            window
              .atob(res.data)
              .split('')
              .map(function (c) {
                return c.charCodeAt(0)
              })
          )
          res.data = bytes
          fileDownload(res)
        } else {
          self.$message.error(res.message)
        }
      }
    },
    is(type, row) {
      this.drawerType = type
      this.drawerVisible = true
      this.activeName = ['first']
      this.formData = JSON.parse(JSON.stringify(row))
      this.formData.circuitGenerationModuleChipMap = new Map()
      this.formData.addMappingArray = []
      this.formData.deleteMappingIdArray = []
      this.tableData = this.formData.circuitGenerationModuleChipList
      if (row.type === 1) {
        this.clockParameters = row.clockParameters
        let clockFormData = {}
        row.clockParameters.forEach((item) => {
          clockFormData[item.symbol] = ['boolean'].includes(item.dataType)
            ? item.defaultValue === 'false'
              ? false
              : Boolean(item.defaultValue)
            : item.defaultValue ?? undefined
        })
        this.clockFormData = clockFormData
        this.$nextTick(() => {
          this.$refs.clockSetting.getRealFormFields()
        })
      } else {
        this.clockParameters = []
        this.clockFormData = {}
      }
      this.$nextTick(() => {
        this.$refs.formData.clearValidate()
      })
    },
    querySearch(queryString, cb) {
      var restaurants = this.categoryList
      var results = queryString
        ? restaurants.filter((value) => {
            return value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
          })
        : restaurants
      // 调用 callback 返回建议列表的数据
      cb(
        results.map((item) => {
          return { value: item }
        })
      )
    },
    handleChange(val) {
      if (val === 1) {
        this.formData.clockParameterFiles = []
      } else {
        this.formData.performanceParameterFiles = []
      }
    },
    handleExceed(files, fileName) {
      this.$refs[fileName].clearFiles()
      this.handleUploadFiles({ file: files[0] }, fileName)
    },
    // 上传前校验
    handleCheck(params) {
      var suffix = params.file.name.substring(params.file.name.lastIndexOf('.')) // .txt
      const isLimit = params.file.size / 1024 / 1024 < 20
      var accept = this.uploadAccept.split(',')
      if (accept.includes(suffix)) {
        if (!isLimit) {
          this.$notify.error('上传文件大小不能超过 20MB!')
          return false
        } else {
          return true
        }
      } else {
        this.$notify.error('上传文件不符合上传格式!')
        return false
      }
    },
    // 图片上传
    handleUploadFiles(require, fileName) {
      let fileDom = this.$refs[fileName].uploadFiles
      let check = this.handleCheck(require)
      if (!check) {
        fileDom.splice(fileDom.length - 1, 1)
        return
      }

      if (defaultSettings.isWPF || defaultSettings.isCEF) {
        this.uploadFileSetting = {
          fileName,
          require
        }
        let self = this
        this.uploadFileRequestId = generateUUID()
        let reader = new FileReader() // new一个FileReader实例
        reader.readAsDataURL(require.file)
        reader.onload = function () {
          //   读取文件获得的对象
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/files/upload',
            RequestMethod: 'POST',
            Headers: {
              // contentType: 'multipart/form-data'
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: {
              fileName: require.file.name,
              fileContent: reader.result.split(',')[1]
            },
            WebInfo: {
              requestId: self.uploadFileRequestId
            }
          }
          postMessage(message)
        }
      } else {
        let formData = new FormData()
        formData.append('file', require.file)
        uploadFile(formData)
          .then((res) => {
            this.$set(this.formData, fileName, [
              {
                uid: require.file.uid,
                fileType: res.data.fileType,
                name: res.data.name,
                fileName: res.data.name,
                url: res.data.url,
                path: res.data.url
              }
            ])
            this.$set(this.formData, fileName + 'Base64', res.data.base64)
            this[fileName + 'Timer'] = new Date().getTime()
          })
          .catch(() => {
            this.$message.error('上传失败')
          })
      }
    },
    handleDel(fileName) {
      this.formData[fileName] = []
      this.formData[fileName + 'Base64'] = ''
      this[fileName + 'Timer'] = new Date().getTime()
    },
    handleClick(name, data = null) {
      if (name === 'download') {
        if (defaultSettings.isWPF || defaultSettings.isCEF) {
          this.downloadFileRequestId = generateUUID()
          let message = {
            RequestUrl: process.env.VUE_APP_URL + '/files/download',
            RequestMethod: 'POST',
            Headers: {
              contentType: 'application/json'
            },
            QueryParameter: {},
            RequestBody: { files: this.formData.chipDefinitionFiles },
            WebInfo: {
              requestId: this.downloadFileRequestId
            }
          }
          postMessage(message)
        } else {
          downLoadFile(
            process.env.VUE_APP_BASE_API + this.formData.chipDefinitionFiles?.[0]?.path,
            this.formData.chipDefinitionFiles?.[0]?.fileName
          )
        }
      } else if (name === 'parameters') {
        this.$refs.clockConfigurationParameters.is(this.drawerType, this.clockParameters)
      } else if (name === 'updateClockParameters') {
        this.clockParameters = data
        let clockFormData = {}
        data.forEach((item) => {
          clockFormData[item.symbol] =
            item.dataType === 'boolean'
              ? item.defaultValue === 'false'
                ? false
                : Boolean(item.defaultValue)
              : item.defaultValue
        })
        this.clockFormData = clockFormData
        this.$nextTick(() => {
          this.$refs.clockSetting.getRealFormFields()
        })
      } else if (name === 'submit') {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            let params = {
              ...this.formData,
              category: this.formData.displayCategory,
              clockParameters: this.clockParameters.map((item) => {
                return {
                  ...item,
                  defaultValue: this.clockFormData[item.symbol]
                }
              }),
              pinFilesBase64: '',
              pinFiles: this.formData.pinFiles.map((item) => {
                return {
                  ...item,
                  base64: ''
                }
              }),
              clockParameterFilesBase64: '',
              clockParameterFiles: this.formData.clockParameterFiles?.map((item) => {
                return {
                  ...item,
                  base64: ''
                }
              }),
              performanceParameterFilesBase64: '',
              performanceParameterFiles: this.formData.performanceParameterFiles?.map((item) => {
                return {
                  ...item,
                  base64: ''
                }
              }),
              mapping: this.tableData
            }
            if (defaultSettings.isWPF || defaultSettings.isCEF) {
              this.updateChipRequestId = generateUUID()
              let message = {
                RequestUrl: process.env.VUE_APP_URL + '/chip/update',
                RequestMethod: 'POST',
                Headers: {
                  contentType: 'application/json'
                },
                QueryParameter: {},
                RequestBody: params,
                WebInfo: {
                  requestId: this.updateChipRequestId
                }
              }
              postMessage(message)
            } else {
              updateChip(params).then((res) => {
                if (res.success) {
                  this.drawerVisible = false
                  this.$notify.success('修改芯片信息成功')
                  this.$emit('refresh', this.formData.type, this.formData.displayCategory)
                } else {
                  this.$notify.error(res.message)
                }
              })
            }
          }
        })
      } else if (name === 'deleteMapping') {
        this.formData.circuitGenerationModuleChipList = this.formData.circuitGenerationModuleChipList.filter(
          (item, index) => index !== data.$index
        )
        this.tableData = this.formData.circuitGenerationModuleChipList
      } else if (name === 'addMapping') {
        this.formData.circuitGenerationModuleChipList.push({
          model: ''
        })
      }
    },
    handleInputChange(row, index) {
      // 尝试找到index相同的数据，直接替换model的值
      const existingItem = this.formData.circuitGenerationModuleChipMap.get(index)
      if (existingItem) {
        existingItem.model = row.model
      } else {
        this.formData.addMappingArray.push({
          // 如果有id，说明是已经存在的数据，需要将isEdit设置为true
          id: row?.id || null, // 使用可选链，如果 row.id 不存在，返回 null
          model: row.model,
          index: index,
          isEdit: Boolean(row?.id) // 将 undefined 转换为布尔值，确保 isEdit 为 true 或 false
        })
        this.formData.circuitGenerationModuleChipMap.set(index, this.formData.addMappingArray[this.formData.addMappingArray.length - 1])
      }
    }
  }
}
</script>

<style lang="less" scoped>
.drawerForm {
  display: flex;
  flex-direction: column;
  height: 100%;
  color: #303453;
  /deep/label {
    font-weight: 400;
    padding-bottom: 0;
  }
}
.drawerFooter {
  justify-content: right;
  padding: 20px;
}
.pageTitle {
  padding-top: 15px;
  padding-left: 24px;
  font-size: 16px;

  .titleText {
    display: inline;
    padding-right: 20px;
    font-weight: bold;
  }
}
.mainContent {
  margin: 20px 24px 0;
  height: calc(100% - 120px);
  overflow-y: auto;
  /deep/.el-collapse-item__header {
    font-weight: 600;
    font-size: 15px;
    .el-icon-arrow-right {
      font-size: 13px;
    }
  }
}
.w100 {
  width: 100%;
}
.picture {
  width: 100%;
  // height: 300px;
  border: 1px solid #ddd;
  padding: 10px;
}

/deep/.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 446px;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}
</style>
